
package privatemessanger;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class contains the history log.
 * @author  Erez Fatal, Oren Slor, Elad Yanai, Sigal Agami, Chen Ben Shabat,
 *          Inbar Pardo, Islamm Heralla, Ziv Hadary, Oren Shalev, Ortal David.
 */
public class Log
{
    private File _f;
    private String PATH = "history/";
    private String SFX = ".txt";
    private  BufferedWriter out;

    public Log(){}

    /**
     * For every message that i get, add it to the log file if there is one or creates a new one if there is no old one.
     * @param msg
     */
    public void getMsg(Message msg)
    {
         try {
                new File(PATH).mkdir();
            } catch (Exception e){} //Catch exception if any
        try {
            // Create file
           out = new BufferedWriter(new FileWriter(PATH+msg.getSenderName()+msg.getSenderID()+SFX,true));
           writeToLog(msg);
        } catch (Exception e){ System.err.println("Error: " + e.getMessage()); }  //Catch exception if any
    }

    /**
     * For every message that i send, look for the file and add the message into it, if there is no file, create it.
     * @param msg
     */
    public void sendMsg(Message msg)
    {
        try{
            new File(PATH).mkdir();
        }catch (Exception e){} //Catch exception if any
        try{
            // Create file
           out = new BufferedWriter(new FileWriter(PATH+msg.getReceiverName()+msg.getReceiverID()+SFX,true));
           writeToLog(msg);
            //Catch exception if any
        }catch (Exception e){ System.err.println("Error: " + e.getMessage()); }
    }

    /**
     * Does the actual writting to the log file.
     * @param msg
     */
    private void writeToLog(Message msg)
    {
        try {
            out.write("Date:"+msg.getTime()+", To:"+msg.getReceiverName()+", From:"+msg.getSenderName()+", Message:"+msg.getMessage());
            out.newLine();
        } catch (IOException ex) { Logger.getLogger(Log.class.getName()).log(Level.SEVERE, null, ex); }
    }

    /**
     * Close the log file when done, this way, you can enter the log file threw notepad even when the conversation is alive.
     */
    public void closeLog()
    {
        try {
            out.close();
        } catch (IOException ex) { Logger.getLogger(Log.class.getName()).log(Level.SEVERE, null, ex); }
    }
}
